# Load necessary libraries
library(tidyverse)
library(fixest)
library(texreg)

## set working directory to replication folder:


# Load cleaned SOEP data
soep <- readRDS("data/soep_panel_bjps.rds")

# -----------------------
# TABLE 1: Five models of CDU/CSU shift types
# -----------------------

result_to_cdu <- feols(to_cdu ~ greens_first_entry_st_parl + greens_other_entry_st_parl + greens_exit_st_parl | pid + year, cluster = ~state_id, data = soep)
result_none_cdu <- feols(none_cdu ~ greens_first_entry_st_parl + greens_other_entry_st_parl + greens_exit_st_parl | pid + year, cluster = ~state_id, data = soep)
result_estab_cdu <- feols(estab_cdu ~ greens_first_entry_st_parl + greens_other_entry_st_parl + greens_exit_st_parl | pid + year, cluster = ~state_id, data = soep)
result_left_cdu <- feols(left_cdu ~ greens_first_entry_st_parl + greens_other_entry_st_parl + greens_exit_st_parl | pid + year, cluster = ~state_id, data = soep)
result_right_cdu <- feols(right_cdu ~ greens_first_entry_st_parl + greens_other_entry_st_parl + greens_exit_st_parl | pid + year, cluster = ~state_id, data = soep)

texreg(
  list(result_to_cdu, result_none_cdu, result_estab_cdu, result_left_cdu, result_right_cdu),
  custom.model.names = c("Overall Shift", "No Party ID", "Estab. Party ID", "Left Party ID", "Right Party ID"),
  custom.coef.names = c("First Green Entry", "Other Green Entry", "Green Exit"),
  omit.coef = "Intercept",
  file = "output/tables/appendix_table_d6.tex"
)

# -----------------------
# TABLE 2: Subsample analysis (from no ID to CDU/CSU)
# -----------------------

result_east <- feols(none_cdu ~ greens_first_entry_st_parl + greens_other_entry_st_parl + greens_exit_st_parl | pid + year, cluster = ~state_id, data = soep[soep$east == 1,])
result_west <- feols(none_cdu ~ greens_first_entry_st_parl + greens_other_entry_st_parl + greens_exit_st_parl | pid + year, cluster = ~state_id, data = soep[soep$east == 0,])
result_pre1998 <- feols(none_cdu ~ greens_first_entry_st_parl + greens_other_entry_st_parl + greens_exit_st_parl | pid + year, cluster = ~state_id, data = soep[soep$year < 1998,])

texreg(
  list(result_east, result_west, result_pre1998),
  custom.model.names = c("Sample East", "Sample West", "Sample pre1998"),
  custom.coef.names = c("First Green Entry", "Other Green Entry", "Green Exit"),
  omit.coef = "Intercept",
  file = "output/tables/appendix_table_d7.tex"
)

